import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Table, Popconfirm, message, Empty } from 'antd';
import { deleteTarget } from '@api/task';
import Tag from '@components/tag';
import { connect } from 'react-redux';
import IpSettingModal from '../target-setting-modal';
import _ from 'lodash';
import './index.less';

const prefixCls = 'target-manage-table';

class IpManageTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ipManageModalVisible: false,
      detail: {}
    };
  }

  deleteTarget = body => {
    deleteTarget(body)
      .then(() => {
        this.props.getTargetList();
        message.success('删除成功');
      })
      .catch(() => {
        message.erroe('删除失败');
      });
  };

  changeModalVisible = (visible, record) => {
    this.setState({
      ipManageModalVisible: visible,
      detail: record
    });
  };

  render() {
    const { ipManageModalVisible } = this.state;
    const { loading, data, pagination, onTableChange, tags, tagIdsIndexMap } = this.props;
    const columns = [
      {
        title: '名称',
        key: 'name',
        width: '15%',
        render: detail => {
          const availableTags = _.get(detail, 'tagOids', [])
            .map(tagId => _.get(tags, tagIdsIndexMap[tagId]))
            .filter(Boolean);
          return (
            <div className="name-wrapper">
              <span className="name">{_.get(detail, 'name', '-')}</span>
              {availableTags.map(tag => {
                const { name, color, _id } = tag;
                // eslint-disable-next-line
                return <Tag key={_id} value={name} color={color} />;
              })}
            </div>
          );
        }
      },
      {
        title: '目标组',
        dataIndex: 'ips',
        width: '30%',
        render: ips => {
          return (
            <div style={{ wordWrap: 'break-word', wordBreak: 'break-all' }}>
              {ips.map((item, index) => (
                <span key={index} className={`${prefixCls}-ips-span`}>
                  {item}
                </span>
              ))}
            </div>
          );
        }
      },
      {
        title: '所属部门',
        key: 'organization',
        render: detail => {
          const organizations = _.get(detail, 'organization.pathObjs', [])
            .map(i => i.name)
            .concat(_.get(detail, 'organization.name'))
            .filter(Boolean)
            .join('/');
          return organizations ? (
            <div className="organization">{organizations}</div>
          ) : (
            '暂无所属部门'
          );
        }
      },
      {
        title: '管理员',
        dataIndex: 'staff',
        render: staff => {
          const name = _.get(staff, 'nickname');
          return name ? <div>{name}</div> : '暂无管理员';
        }
      },
      {
        title: '创建人',
        dataIndex: 'user',
        className: `${prefixCls}-user`,
        render: user => {
          const name = _.get(user, 'username');
          const nickname = _.get(user, 'nickname');
          return name && nickname ? (
            <div>
              {nickname}({name})
            </div>
          ) : (
            '暂无创建人'
          );
        }
      },
      {
        title: '操作',
        dataIndex: 'operations',
        width: '10%',
        render: (operations, record) => {
          return (
            <div>
              <a className="be-color" onClick={() => this.changeModalVisible(true, record)}>
                编辑
              </a>
              <Popconfirm
                placement="bottomRight"
                title={'确定删除吗'}
                onConfirm={() => this.deleteTarget({ ip_id: record._id })}
                okText="确定"
                cancelText="取消"
              >
                <a style={{ marginLeft: 10, color: '#F04038' }}>删除</a>
              </Popconfirm>
            </div>
          );
        }
      }
    ];

    return (
      <div className={`${prefixCls}`}>
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={data}
          onChange={onTableChange}
          loading={{ spinning: loading, tip: '加载中' }}
          locale={{
            emptyText: (
              <Empty
                description={loading ? ' ' : '暂无数据'}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )
          }}
        />
        <IpSettingModal
          modalVisible={ipManageModalVisible}
          changeModalVisible={this.changeModalVisible}
          getTargetList={this.props.getTargetList}
          detail={this.state.detail}
          staffList={this.props.staffList}
        />
      </div>
    );
  }
}

IpManageTable.propTypes = {
  onTableChange: PropTypes.function,
  changeModalVisible: PropTypes.function,
  total: PropTypes.number,
  data: PropTypes.array,
  pagination: PropTypes.object,
  getTargetList: PropTypes.function,
  loading: PropTypes.boolean,
  tags: PropTypes.array,
  staffList: PropTypes.array,
  tagIdsIndexMap: PropTypes.object
};

const mapStateToProps = state => {
  return {
    tags: _.get(state, 'tag.tags', []),
    tagIdsIndexMap: _.get(state, 'tag.tagIdsIndexMap', {})
  };
};

export default connect(
  mapStateToProps,
  null
)(IpManageTable);
